import {
  createRouter,
  createWebHashHistory
} from 'vue-router'
const routes = [{
    path: "/",
    name: "首页",
    component: () => import('../views/layout'),
    children:[
      {
        path:'/home',
        name:"首页",
        component:() => import('../views/home/')
      },{
        path:"/user",
        name:"用户管理",
        component:() => import('../views/user/')
      },
      {
        path:'/productType',
        name:"商品类型管理",
        component:() => import('../views/productType'),
      }
    ]
  }, 
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login'),
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

import api from '@/api/index'
router.beforeEach((to, from, next) => {
    // 1. 判断该路由是否需要登录权限
    if (to.name === 'login') {
        // 不需要登录权限页面直接跳转
        next()
    }

    // 2 需要登录，判断本地是否存在token
    if (!localStorage.getItem(process.env.VUE_APP_BASE_TOKEN)) {
        // 没有token,跳转到登陆页面
        next({ path: "/login" })
    }

    // 3 有token，判断本地是否有用户信息
    if (!localStorage.getItem(process.env.VUE_APP_BASE_TOKEN)) { 
        // 不存在用户信息，通过token获取用户信息
        api.getUserInfo().then(result => {
            if (result.success) {
                // 获取用户信息成功，保存用户信息并跳转目标路由
                localStorage.setItem(process.env.VUE_APP_BASE_USER, JSON.stringify(result.data));
            } else {
                // 获取用户信息失败，跳转登录页
                next({path: '/login'})
            }
        })
    }
    //
    next()
})
export default router